import axios from 'axios'
import $message from 'ant-design-vue/lib/message'
import $storage from "@/lib/storage";

const $http = axios.create({
  responseType: 'json',
  baseURL: '/ops/api',
  timeout: 10000
});

// 默认配置项
const defaultConfig = {
  // 是否需要登陆
  auth: true,
  // 超时时间
  timeout: 10000,
  // 请求头
  contentType: 'application/json',
  // 跳过响应拦截器异常处理提示
  skipErrorMessage: false,
  // 跳过响应拦截器
  skipRespInterceptor: false
};

/**
 * get 请求
 * @param url
 * @param params
 * @param config
 * @returns {Promise<unknown>}
 */
const $get = (url, params = {}, config = {}) => {
  config.params = params;
  return new Promise((resolve, reject) => {
    $http.get(url, fillDefaultConfig(config))
      .then(res => resolve(res))
      .catch(res => reject(res))
  })
};

/**
 * post请求
 * @param url
 * @param data
 * @param config
 * @returns {Promise<unknown>}
 */
const $post = (url, data = {}, config = {}) => {
  return new Promise((resolve, reject) => {
    $http.post(url, data, fillDefaultConfig(config))
      .then(res => resolve(res))
      .catch(err => reject(err))
  })
};

/**
 * 设置默认配置项
 * @param config
 * @returns {*}
 */
function fillDefaultConfig(config) {
  for (const defaultConfigKey in defaultConfig) {
    if (!(defaultConfigKey in config)) {
      config[defaultConfigKey] = defaultConfig[defaultConfigKey];
    }
  }
  return config;
}

/**
 * 配置请求拦截器
 */
$http.interceptors.request.use(
  config => {
    const loginToken = $storage.get($storage.keys.LOGIN_TOKEN);
    config.headers['Content-Type'] = config.contentType;
    config.headers[$storage.keys.LOGIN_TOKEN] = loginToken;   // 请求头设置token

    return config;
  }, error => {
    return Promise.reject(error);
  }
);



/**
 * 配置响应拦截器
 */
$http.interceptors.response.use(resp => {
  // 判断data
  const respData = resp.data;
  if (!respData || !respData.code) {
    $message.warning('请求无效');
    return Promise.reject(resp);
  }

  switch (respData.code) {
    case 200:
      // 正常返回
      return respData;
    case 401:
      $message.warning('用户名或密码错误');
  }

});


export default {
  $get,
  $post
}
